package fischl;

import fischl.log.Log;
import fischl.log.LogFactory;
import fischl.log.SysoutLogs;
import fischl.web.*;

public final class Application {
  public static void main(String[] args) throws Exception {
    // initialize logger
    SysoutLogs.init();
    Log log = LogFactory.get("main");

    // print usages
    System.out.println("使用方法: java -jar fischl.jar <d|h> <extra-file-path> <disableBuiltinRoom> <huyaDanmuUrl>");
    System.out.println("<d|h>                指定平台，默认是斗鱼");
    System.out.println("<extra-file-path>    额外房间配置文件");
    System.out.println("<disableBuiltinRoom> 禁用内置的配置文件");
    System.out.println("<huyaDanmuUrl>       虎牙弹幕服务地址");

    // parse arguments
    if (args.length > 0) {
      Config.isDouyu = "d".equalsIgnoreCase(args[0]);
    }
    if (args.length > 1) {
      Config.extraRoomPath = args[1];
    }
    if (args.length > 2) {
      Config.disableBuiltinRoom = "disableBuiltinRoom".equals(args[2]);
    }
    if (args.length > 3) {
      Config.huyaDanmuUrl = args[3];
    }
    log.i("Config loaded.");
    Config.printConfig();

    // preload resources
    RoomLoader.load();
    VideoMarker.getAllMarkedIds();

    // loading douyu record data
    log.i("loading started...");
    long now = System.currentTimeMillis();
    Platform.init(Config.isDouyu).doWatch();
    log.i("data loaded in {}ms", System.currentTimeMillis() - now);

    // start web server
    HttpServer server = new HttpServer(9000);
    server.addHandler(new IndexHandler());
    server.addHandler(new DanmuHandler());
    server.addHandler(new MarkerHandler());
    server.addHandler(new RoomHandler());
    server.addHandler(new StaticResourceHandler());
    server.start(HttpServer.SOCKET_READ_TIMEOUT, false);

    log.i("Server started at http://localhost:" + server.getListeningPort());
  }
}